/**
 * There are code generation
 */
package com.neusoft.lohas.modules.ivm.service.order;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.service.BaseService;
import com.neusoft.lohas.common.utils.DateUtils;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.modules.ivm.dao.order.OrderDao;
import com.neusoft.lohas.modules.ivm.dao.order.OrderDetailDao;
import com.neusoft.lohas.modules.ivm.dao.order.OrderDetailItemDao;
import com.neusoft.lohas.modules.ivm.entity.order.Order;
import com.neusoft.lohas.modules.ivm.entity.order.OrderDetail;
import com.neusoft.lohas.modules.ivm.entity.order.OrderDetailItem;
import com.neusoft.lohas.modules.ivm.entity.purchase.PurchaseDetail;
import com.neusoft.lohas.modules.ivm.enums.order.OrderTypeEnum;
import com.neusoft.lohas.modules.ivm.enums.order.PayStatusEnum;
import com.neusoft.lohas.modules.ivm.enums.order.PayTypeEnum;

/**
 * 商品订单Service
 * @author Jackie.Liu
 * @version 2014-12-16
 */
@Component
@Transactional(readOnly = true)
public class OrderService extends BaseService {

	@Autowired
	private OrderDao orderDao;
	@Autowired
	private OrderDetailDao orderDetailDao;
	@Autowired
	private OrderDetailItemDao orderDetailItemDao;
	
	public Order get(String id) {
		return orderDao.get(id);
	}
	
	/**
	 * 获取订单列表
	 * @param page
	 * @param order
	 * @param createStartDate
	 * @param createEndDate
	 * @param hopeStartDate
	 * @param hopeEndDate
	 * @return
	 */
	public Page<Order> find(Page<Order> page, Order order, String createStartDate, String createEndDate, String hopeStartDate, String hopeEndDate) {
		DetachedCriteria dc = orderDao.createDetachedCriteria();
		if (StringUtils.isNotEmpty(order.getOrderNo())){
			dc.add(Restrictions.like("orderNo", "%"+order.getOrderNo()+"%"));
		}
		if (StringUtils.isNotEmpty(order.getId())){
			dc.add(Restrictions.eq("id", order.getId()));
		}
		if (StringUtils.isNotEmpty(order.getPayType())){
			dc.add(Restrictions.eq("payType", order.getPayType()));
		}
//		if (StringUtils.isNotEmpty(order.getPayStatus())){
//			dc.add(Restrictions.eq("payStatus", order.getPayStatus()));
//		}
		if(StringUtils.isEmpty(order.getOrderType())){
			order.setOrderType("1");
		}
		if (StringUtils.isNotEmpty(order.getOrderType())){
//			dc.add(Restrictions.eq("orderType", order.getOrderType()));
			int type = Integer.valueOf(order.getOrderType());
			if (type==1) { //全部
				
			}else if (type==2) { //待付款
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
				dc.add(Restrictions.eq("payStatus", String.valueOf(PayStatusEnum.NOT_PAY.getStatus())));
				dc.add(Restrictions.and(
					Restrictions.or(
						Restrictions.eq("payType", String.valueOf(PayTypeEnum.ALIPAY.getType())),
						Restrictions.eq("payType", String.valueOf(PayTypeEnum.UNIONPAY.getType())),
						Restrictions.eq("payType", String.valueOf(PayTypeEnum.WECHAT.getType())),
						Restrictions.eq("payType", String.valueOf(PayTypeEnum.CASH_ON_DELIVERY.getType()))
					)
				));
			}else if (type==3) { //待发货
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
				dc.add(Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.READY_FOR_DELIVERY.getType())));
				dc.add(Restrictions.and(
					Restrictions.or(
						Restrictions.and(
							Restrictions.eq("payStatus", String.valueOf(PayStatusEnum.NOT_PAY.getStatus())),
							Restrictions.eq("payType", String.valueOf(PayTypeEnum.CASH_ON_DELIVERY.getType()))
						),
						Restrictions.and(
							Restrictions.eq("payStatus", String.valueOf(PayStatusEnum.PAYED.getStatus())),
							Restrictions.or(
								Restrictions.eq("payType", String.valueOf(PayTypeEnum.ALIPAY.getType()))
							),
							Restrictions.or(
								Restrictions.eq("payType", String.valueOf(PayTypeEnum.UNIONPAY.getType()))
							),
							Restrictions.or(
								Restrictions.eq("payType", String.valueOf(PayTypeEnum.WECHAT.getType()))
							)
						)
					)
				));
			}else if (type==4) { //待收货
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
				dc.add(Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.DELIVERYING.getType())));
			}else if (type==5) { //已完成
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
				dc.add(Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.DELIVERIED.getType())));
			}else if (type==6) { //已取消
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_DELETE));
			}
		}
		//下单日期判断查询
		if(!"".equals(createStartDate) && !"".equals(createEndDate)){
			dc.add(Restrictions.between("createDate", DateUtils.getDateStart(DateUtils.parseDate(createStartDate)), DateUtils.getDateEnd(DateUtils.parseDate(createEndDate))));
		}else if("".equals(createStartDate) && !"".equals(createEndDate)){
			dc.add(Restrictions.lt("createDate", DateUtils.getDateEnd(DateUtils.parseDate(createEndDate))));
		}else if(!"".equals(createStartDate) && "".equals(createEndDate)){
			dc.add(Restrictions.gt("createDate", DateUtils.getDateStart(DateUtils.parseDate(createStartDate))));
		}
		//要求送货日期查询
		if(!"".equals(hopeStartDate) && !"".equals(hopeEndDate)){
			dc.add(Restrictions.or(
					Restrictions.and(
							Restrictions.eq("deliveryOption", "today"),
							Restrictions.between("createDate", DateUtils.getDateStart(DateUtils.parseDate(hopeStartDate)), DateUtils.getDateEnd(DateUtils.parseDate(hopeEndDate)))
					),
					Restrictions.and(
							Restrictions.eq("deliveryOption", "tomorrow"),
							Restrictions.between("createDate", DateUtils.GetLastDate(DateUtils.getDateStart(DateUtils.parseDate(hopeStartDate)),-1), DateUtils.GetLastDate(DateUtils.getDateEnd(DateUtils.parseDate(hopeEndDate)),-1))
					)
			));
		}else if("".equals(hopeStartDate) && !"".equals(hopeEndDate)){
			dc.add(Restrictions.or(
					Restrictions.and(
							Restrictions.eq("deliveryOption", "today"),
							Restrictions.lt("createDate", DateUtils.getDateEnd(DateUtils.parseDate(hopeEndDate)))
					),
					Restrictions.and(
							Restrictions.eq("deliveryOption", "tomorrow"),
							Restrictions.lt("createDate", DateUtils.GetLastDate(DateUtils.getDateEnd(DateUtils.parseDate(hopeEndDate)),-1))
					)
			));
		}else if(!"".equals(hopeStartDate) && "".equals(hopeEndDate)){
			dc.add(Restrictions.or(
					Restrictions.and(
							Restrictions.eq("deliveryOption", "today"),
							Restrictions.gt("createDate", DateUtils.getDateStart(DateUtils.parseDate(hopeStartDate)))
					),
					Restrictions.and(
							Restrictions.eq("deliveryOption", "tomorrow"),
							Restrictions.gt("createDate", DateUtils.GetLastDate(DateUtils.getDateStart(DateUtils.parseDate(hopeStartDate)),-1))
					)
			));
		}
		dc.add(Restrictions.eq("merchant.id", order.getMerchant().getId()));
		dc.addOrder(org.hibernate.criterion.Order.desc("createDate"));
		dc.addOrder(org.hibernate.criterion.Order.asc("payStatus"));
		dc.addOrder(org.hibernate.criterion.Order.asc("orderType"));
		return orderDao.find(page, dc);
	}
	
	//search  0:分页查询，1全部查询
	public Page<Order> find(Page<Order> page, Order order, String createStartDate, String createEndDate, String searchParam, String[] timeSlot, int search) {
		DetachedCriteria dc = orderDao.createDetachedCriteria();
		if(StringUtils.isEmpty(order.getOrderType())){
			order.setOrderType("1");
		}
		if (StringUtils.isNotEmpty(order.getOrderType())){
			int type = Integer.valueOf(order.getOrderType());
			if (type==1) { //全部
				
			}else if (type==2) { //待付款
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
				dc.add(Restrictions.eq("payStatus", String.valueOf(PayStatusEnum.NOT_PAY.getStatus())));
				dc.add(Restrictions.and(
					Restrictions.or(
						Restrictions.eq("payType", String.valueOf(PayTypeEnum.ALIPAY.getType())),
						Restrictions.eq("payType", String.valueOf(PayTypeEnum.UNIONPAY.getType())),
						Restrictions.eq("payType", String.valueOf(PayTypeEnum.WECHAT.getType())),
						Restrictions.eq("payType", String.valueOf(PayTypeEnum.CASH_ON_DELIVERY.getType()))
					)
				));
			}else if(type==8){//待确认
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
				dc.add(Restrictions.eq("confirm", "0"));
			}else if (type==3) { //待发货
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
				dc.add(Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.READY_FOR_DELIVERY.getType())));
				dc.add(Restrictions.and(
					Restrictions.or(
						Restrictions.and(
							Restrictions.eq("payStatus", String.valueOf(PayStatusEnum.NOT_PAY.getStatus())),
							Restrictions.eq("payType", String.valueOf(PayTypeEnum.CASH_ON_DELIVERY.getType()))
						),
						Restrictions.and(
							Restrictions.eq("payStatus", String.valueOf(PayStatusEnum.PAYED.getStatus())),
							Restrictions.or(
								Restrictions.eq("payType", String.valueOf(PayTypeEnum.ALIPAY.getType()))
							),
							Restrictions.or(
								Restrictions.eq("payType", String.valueOf(PayTypeEnum.UNIONPAY.getType()))
							),
							Restrictions.or(
								Restrictions.eq("payType", String.valueOf(PayTypeEnum.WECHAT.getType()))
							)
						)
					)
				));
			}else if (type==4) { //待收货
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
				dc.add(Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.DELIVERYING.getType())));
			}else if (type==9) { //结款
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
				dc.add(Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.DELIVERIED.getType())));
				dc.add(Restrictions.eq("finish", "0"));
			}else if(type==5){ //已完成
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
				dc.add(Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.DELIVERIED.getType())));
				dc.add(Restrictions.eq("finish", "1"));
			}else if (type==6) { //已取消
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_DELETE));
			}else if(type==7){//处理中（送货员签出前）
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
				dc.add(Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.READY_FOR_DELIVERY.getType())));
				dc.add(Restrictions.eq("finish", "0"));
				dc.add(Restrictions.eq("confirm", "1"));
			}else if(type==10){//处理中（送货员签出后）
				dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
				dc.add(Restrictions.eq("orderType", String.valueOf(OrderTypeEnum.DELIVERYING.getType())));
				dc.add(Restrictions.eq("finish", "0"));
				dc.add(Restrictions.eq("confirm", "1"));
			}
		}
		//下单日期判断查询
//		if(!"".equals(createStartDate) && !"".equals(createEndDate)){
//			dc.add(Restrictions.between("createDate", DateUtils.getDateStart(DateUtils.parseDate(createStartDate)), DateUtils.getDateEnd(DateUtils.parseDate(createEndDate))));
//		}else if("".equals(createStartDate) && !"".equals(createEndDate)){
//			dc.add(Restrictions.lt("createDate", DateUtils.getDateEnd(DateUtils.parseDate(createEndDate))));
//		}else if(!"".equals(createStartDate) && "".equals(createEndDate)){
//			dc.add(Restrictions.gt("createDate", DateUtils.getDateStart(DateUtils.parseDate(createStartDate))));
//		}
		//if (order.getTimeSlot() != null && StringUtils.isNotBlank(order.getTimeSlot().getId())) {
		//	dc.add(Restrictions.eq("timeSlot.id", order.getTimeSlot().getId()));
		//}
		if (order.getDeliveryIndent()!=null && order.getDeliveryIndent().getDeliveryMember()!=null && StringUtils.isNotBlank(order.getDeliveryIndent().getDeliveryMember().getId())) {
			dc.createAlias("deliveryIndent", "deliveryIndent");
			dc.add(Restrictions.eq("deliveryIndent.deliveryMember.id", order.getDeliveryIndent().getDeliveryMember().getId()));
		}
		dc.createAlias("userAddress", "userAddress");
		dc.createAlias("user", "user");
		dc.createAlias("deliveryInfo", "deliveryInfo");
		if (StringUtils.isNotEmpty(searchParam)){
			dc.add(Restrictions.or(
				Restrictions.or(
					Restrictions.like("orderNo", "%"+searchParam+"%")
				),
				Restrictions.or(
					Restrictions.like("userAddress.name", "%"+searchParam+"%")
				),
				Restrictions.or(
					Restrictions.like("userAddress.phone", "%"+searchParam+"%")
				),
				Restrictions.or(
					Restrictions.like("user.name", "%"+searchParam+"%")
				),
				Restrictions.or(
					Restrictions.like("user.phone", "%"+searchParam+"%")
				)
				,Restrictions.or(
					Restrictions.like("deliveryInfo.name", "%"+searchParam+"%")
				),
				Restrictions.or(
					Restrictions.like("deliveryInfo.phone", "%"+searchParam+"%")
				),
				Restrictions.or(
					Restrictions.like("deliveryInfo.address", "%"+searchParam+"%")
				)
			));
		}
		//送货日期判断查询
		if(!"".equals(createStartDate) && !"".equals(createEndDate)){
			dc.add(Restrictions.between("deliveryInfo.deliveryDate", DateUtils.getDateStart(DateUtils.parseDate(createStartDate)), DateUtils.getDateEnd(DateUtils.parseDate(createEndDate))));
		}else if("".equals(createStartDate) && !"".equals(createEndDate)){
			dc.add(Restrictions.lt("deliveryInfo.deliveryDate", DateUtils.getDateEnd(DateUtils.parseDate(createEndDate))));
		}else if(!"".equals(createStartDate) && "".equals(createEndDate)){
			dc.add(Restrictions.gt("deliveryInfo.deliveryDate", DateUtils.getDateStart(DateUtils.parseDate(createStartDate))));
		}
		//送货时间判断
		if(timeSlot.length>0){
			String[] timeSlots = new String[2*timeSlot.length];
			for(int i=0;i<timeSlot.length;i++){
				timeSlots[i]=timeSlot[i];
			}
			for(int i=0;i<timeSlot.length;i++){
				timeSlots[timeSlot.length+i]=timeSlot[i].replace(":", "");
			}
			dc.add(Restrictions.in("deliveryInfo.deliveryTime", timeSlots));
		}
		dc.add(Restrictions.eq("merchant.id", order.getMerchant().getId()));
		dc.addOrder(org.hibernate.criterion.Order.desc("createDate"));
		dc.addOrder(org.hibernate.criterion.Order.asc("payStatus"));
		dc.addOrder(org.hibernate.criterion.Order.asc("orderType"));
		if(search == 1){//全选导出
			page.setPageSize(99999);
			dc.add(Restrictions.eq(com.neusoft.lohas.modules.ivm.entity.order.Order.FIELD_DEL_FLAG, com.neusoft.lohas.modules.ivm.entity.order.Order.DEL_FLAG_NORMAL));
		}
		return orderDao.find(page, dc);
	}
	
	/**
	 * 获取订单商品详情列表/分页查询
	 * @param page
	 * @param order
	 * @return
	 */
	public Page<OrderDetail> findOrderDetails(Page<OrderDetail> page, Order order){
		DetachedCriteria dc = orderDetailDao.createDetachedCriteria();
		dc.add(Restrictions.eq("order.id", order.getId()));
		dc.add(Restrictions.eq(Order.FIELD_DEL_FLAG, Order.DEL_FLAG_NORMAL));
		dc.addOrder(org.hibernate.criterion.Order.desc("id"));
		return orderDetailDao.find(page, dc);
	}
	
	/**
	 * 获取订单商品详情列表/全部查询
	 * @param page
	 * @param order
	 * @return
	 */
	public List<OrderDetail> findOrderDetailList(Order order){
		DetachedCriteria dc = orderDetailDao.createDetachedCriteria();
		dc.add(Restrictions.eq("order.id", order.getId()));
		dc.add(Restrictions.eq(Order.FIELD_DEL_FLAG, Order.DEL_FLAG_NORMAL));
		dc.addOrder(org.hibernate.criterion.Order.desc("id"));
		return orderDetailDao.find(dc);
	}
	
	/**
	 * 获取订单商品备份详情列表/全部查询
	 * @param page
	 * @param order
	 * @return
	 */
	public List<OrderDetailItem> findOrderDetailItemList(Order order){
		DetachedCriteria dc = orderDetailDao.createDetachedCriteria();
		dc.add(Restrictions.eq("order.id", order.getId()));
		dc.add(Restrictions.eq(Order.FIELD_DEL_FLAG, Order.DEL_FLAG_NORMAL));
		dc.addOrder(org.hibernate.criterion.Order.desc("id"));
		return orderDetailItemDao.find(dc);
	}
	
	/**
	 * 获取勾选的订单信息列表
	 * @param page
	 * @param order
	 * @return
	 */
	public List<Order> findSelects(String[] orderIds){
		DetachedCriteria dc = orderDao.createDetachedCriteria();
		dc.add(Restrictions.in("id", orderIds));
		dc.addOrder(org.hibernate.criterion.Order.desc("orderNo"));
		return orderDao.find(dc);
	}
	
	@Transactional(readOnly = false)
	public void save(Order order) {
		orderDao.save(order);
	}
	
	@Transactional(readOnly = false)
	public void save(List<Order> orderList) {
		orderDao.save(orderList);
	}
	
	@Transactional(readOnly = false)
	public void delete(String id) {
		orderDao.deleteById(id);
	}

	@Transactional(readOnly = false)
	public int updateOrderTypeById(String orderId, String status) {
		return orderDao.updateStatusById(orderId, status);
	}
	
	@Transactional(readOnly = false)
	public void finishOrder(String id){
		orderDao.finishOrder(id);
	}
	
	/**
	 * 用户生成采购清单操作的查询
	 * @param orderIds
	 * @return
	 */
	public List<PurchaseDetail> getOrderPurchaseList(String orderIds, String supplierId, int purchaseState, int type) {
		return orderDao.getOrderPurchaseList(orderIds, supplierId, purchaseState, type);
	}
	
}
